package com.epam.ws.anatomist.messaging.dispatcher;

import java.util.HashMap;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.handler.HandlerResolver;

import org.springframework.context.ApplicationContext;

public class ServiceFactory
{
	private ApplicationContext applicationContext;

	private final HashMap<String, Service> SERVICE_MAP = new HashMap<String, Service>();

	private final HashMap<String, ServiceDescriptor> SERVICE_DESCRIPTOR_MAP = new HashMap<String, ServiceDescriptor>();

	public ServiceFactory(ApplicationContext context)
	{
		this.applicationContext = context;
	}

	public QName getPortQName(String serviceConfigName)
	{
		ServiceDescriptor descriptor = getServiceDescriptor(serviceConfigName);
		return descriptor.getPortQname();
	}

	public Service getService(String serviceConfigName)
	{
		if (SERVICE_MAP.containsKey(serviceConfigName))
		{
			return SERVICE_MAP.get(serviceConfigName);
		}
		else
		{
			ServiceDescriptor descriptor = getServiceDescriptor(serviceConfigName);
			Service service = Service.create(descriptor.getWsdlURL(), descriptor.getEndpointQname());
			HandlerResolver handlerResolver = descriptor.getHandleResolver();
			service.setHandlerResolver(handlerResolver);
			SERVICE_MAP.put(serviceConfigName, service);
			return service;
		}
	}

	private ServiceDescriptor getServiceDescriptor(String serviceConfigName)
	{
		if (SERVICE_DESCRIPTOR_MAP.containsKey(serviceConfigName))
		{
			return SERVICE_DESCRIPTOR_MAP.get(serviceConfigName);
		}
		else
		{
			ServiceDescriptor descriptor = getBean(serviceConfigName, ServiceDescriptor.class);
			SERVICE_DESCRIPTOR_MAP.put(serviceConfigName, descriptor);
			return descriptor;
		}
	}

	private <T> T getBean(String name, Class<T> type)
	{
		return (T) applicationContext.getBean(name, type);
	}

}
